package com.example.ipcputest.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * IP信息相关工具类
 */
public class IpUtil {

    private static  String linuxLocalIp;

    public static String getLinuxLocalIp() {
        if (linuxLocalIp != null) {
            return linuxLocalIp;
        }
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                if (intf.isLoopback() || intf.isVirtual() || !intf.isUp() || intf.getName().contains("docker")) {
                    continue;
                }
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        linuxLocalIp = inetAddress.getHostAddress();
                        return linuxLocalIp;
                    }
                }
            }
        } catch (SocketException ignored) {
        }
        return linuxLocalIp;
    }

}
